import axios from 'axios'
import { Message } from 'element-ui'

const http = axios.create({
  baseURL: '/',
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
    sign: 'sign',
    token: 'token',
    timestamp: 'timestamp'
  }
})
// 添加请求拦截器
http.interceptors.request.use(config => {
  // 在发送请求之前做些什么
  config.data = JSON.stringify({data: config.data})
  console.log(config)
  return config
}, error => {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 响应拦截器
// let isExpired=true
http.interceptors.response.use(
  response => {
    // if (response.data.code == 999 && isExpired) {
    //   isExpired=!isExpired
    //   alert(response.data.msg)
    //   setTimeout(()=>{
    //     router.push('/')
    //   },1000)
    // }
    if(response.data?.data && response.data.code === '000000'){
      return { data: JSON.parse(response.data.data), code: response.data.code }
    } else {
      Message(response.data.message)
      return {}
    }
  }  
)
export const buildTree=(arr,id)=>{
  let temp = {}
  let tree = {}
  // 数组转 键值对
  arr.forEach(item => {
    temp[item[id]] = item
  })
  let keys = Object.keys(temp)
  keys.forEach(key => {
    // 获取当前项
    let item = temp[key]
    // 当前项 pId
    let pid = item.parentId
    // 获取父级项
    let pidItem = temp[pid]
    if (pidItem) {
      if (!pidItem.children) {
        pidItem.children = []
      }
      pidItem.children.push(item)
    } else {
      tree[item[id]] = item
    }
  })
  // 对象转数组并返回
  return Object.keys(tree).map(key => tree[key])
}
export default http